package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.shiro.demo.dao.util.Pagination;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Comment;
import org.shiro.demo.entity.CommentReply;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.ICommentReplyService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 评论
 * 
 * @author Chinesejie
 *
 */
@Controller
@RequestMapping(value = "/comment")
public class CommentController {
	@Resource(name = "baseService")
	private IBaseService baseService;

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "commentReplyService")
	private ICommentReplyService commentReplyService;

	/**
	 * 
	 * 增加评论
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object add(Comment comment) {
		ResponseResult rr = new ResponseResult();
		User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
		//支持 空评论，只发图
//		if (StringUtils.isEmpty(comment.getWord())) {
//			rr.setCode(0);
//			rr.setInfo("评论不能为空");
//			return rr;
//		} else {//非空
//			if (comment.getWord().trim().equals("")) {
//				rr.setCode(0);
//				rr.setInfo("评论不能为空");
//				return rr;
//			}
//		}
		User userInDB = userService.getByPhone(currentUser.getPhone());
		comment.setUser_id(currentUser.getPhone());// 发布人
		// 昵称，， 如果没有昵称，那么 手机号 后面几位 去掉。
		if (currentUser.getPhone().equals(currentUser.getUsername())) {
			comment.setUserName(currentUser.getUsername().substring(0, 9) + "****");
		} else {
			comment.setUserName(currentUser.getUsername());
		}
		comment.setUser_image(userInDB.getImage());// 可能 缓存的 image是旧的。 所以到数据库去取
		comment.setPostTime(new Date());
		// 校验 提交的images
		// 是否正确？67e0ee9fc953232c1c59f286d686240f_320_640;67e0ee9fc953232c1c59f286d686240f_320_640

		// "67e0ee9fc953232c1c59f286d686240f_320_640;67e0ee9fc953232c1c59f286d686240f_320_640".split(";")
		// 与
		// "67e0ee9fc953232c1c59f286d686240f_320_640;67e0ee9fc953232c1c59f286d686240f_320_640;".split(";")
		// 结果相同
		if (comment.getImages().endsWith(";")) {
			rr.setCode(0);
			rr.setInfo("图片格式不能是分号 结尾");
			return rr;
		}
		if (!StringUtils.isEmpty(comment.getImages())) {
			String[] images = comment.getImages().split(";");
			for (String im : images) {
				String s[] = im.split("_");
				if (s.length != 3) {
					// TODO 检查图片是否存在
					rr.setCode(0);
					rr.setInfo("图片格式有误");
					return rr;
				}
			}
		} else {// 不能为null
			rr.setCode(0);
			rr.setInfo("图片不能为空");
			return rr;
		}
		try {
			baseService.save(comment);
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(comment);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("success");
			rr.setObject(null);
		}

		return rr;
	}

	/**
	 * 所有评论 分页返回
	 * 
	 * @param current
	 * @param count
	 * @return
	 */
	@RequestMapping(value = "/list")
	public @ResponseBody Object list(@RequestParam(value = "current", required = true) int current, @RequestParam(value = "count", required = true) int count) {
		try {
			String order = "postTime DESC";

			Pagination<Comment> pa = (Pagination<Comment>) baseService.getPagination(Comment.class, null, "ORDER BY o." + order, current, count);
			for (Comment comment : pa.getRecordList()) {
				if (StringUtils.isEmpty(comment.getReplyIds())) {
					comment.setReplys(new ArrayList<CommentReply>());
				} else {
					comment.setReplys(commentReplyService.get(comment));// 会存入缓存
				}
			}
			return new ResponseResult(1, "成功", pa);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "失败", null);

		}

	}

	/**
	 * 我的评论。不需要登录
	 * 
	 * @param phone
	 * @param current
	 * @param count
	 * @return
	 */
	@RequestMapping(value = "/minelist")
	public @ResponseBody Object minelist(@RequestParam(value = "phone", required = true) String phone, @RequestParam(value = "current", required = true) int current, @RequestParam(value = "count", required = true) int count) {
		try {

			String order = "postTime DESC";
			List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
			queryConditions.add(new QueryCondition("user_id", QueryCondition.EQ, phone));
			Pagination<Comment> pa = (Pagination<Comment>) baseService.getPagination(Comment.class, queryConditions, "ORDER BY o." + order, current, count);
			for (Comment comment : pa.getRecordList()) {
				if (StringUtils.isEmpty(comment.getReplyIds())) {
					comment.setReplys(new ArrayList<CommentReply>());
				} else {
					comment.setReplys(commentReplyService.get(comment));// 会存入缓存
				}
			}
			return new ResponseResult(1, "成功", pa);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "失败", null);
		}

	}

	/**
	 * 根据product_id 获取评论列表
	 * 
	 * @param product_id
	 * @param current
	 * @param count
	 * @return
	 */
	@RequestMapping(value = "/listByPid")
	public @ResponseBody Object listByPid(@RequestParam(value = "pid", required = true) String product_id, @RequestParam(value = "current", required = true) int current, @RequestParam(value = "count", required = true) int count) {
		try {

			String order = "postTime DESC";
			List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
			queryConditions.add(new QueryCondition("product_id", QueryCondition.EQ, product_id));
			Pagination<Comment> pa = (Pagination<Comment>) baseService.getPagination(Comment.class, queryConditions, "ORDER BY o." + order, current, count);
			for (Comment comment : pa.getRecordList()) {
				if (StringUtils.isEmpty(comment.getReplyIds())) {
					comment.setReplys(new ArrayList<CommentReply>());
				} else {
					comment.setReplys(commentReplyService.get(comment));// 会存入缓存
				}
			}
			return new ResponseResult(1, "成功", pa);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseResult(0, "失败", null);
		}

	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object deleteCategory(@RequestParam(value = "id", required = true) long id) {
		ResponseResult rr = new ResponseResult();
		Comment comment = baseService.getById(Comment.class, id);
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		if (!comment.getUser_id().equals(user.getPhone())) {
			rr.setInfo("评论不是你家的");
			return rr;
		}
		try {
			baseService.delete(Comment.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}
		rr.setCode(1);
		rr.setInfo("success");
		return rr;
	}

	// 添加回复。
	/**
	 * 
	 * 添加回复。
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/reply")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("customer")
	public Object reply(CommentReply commentReply) {
		ResponseResult rr = new ResponseResult();
		User currentUser = (User) SecurityUtils.getSubject().getPrincipal();

		Comment comment = baseService.getById(Comment.class, commentReply.getCommentId());
		if (comment == null) {
			rr.setInfo("评论不存在");
			return rr;
		}

		if (StringUtils.isEmpty(commentReply.getWord())) {
			rr.setInfo("回复不能为空");
			return rr;
		}
		if (commentReply.getWord().length() > 200) {
			rr.setInfo("回复长度不能大于200");
			return rr;
		}

		commentReply.setPostTime(new Date());
		commentReply.setUser_id(currentUser.getPhone());
		commentReply.setUser_image(currentUser.getImage());
		// 昵称，， 如果没有昵称，那么 手机号 后面几位 去掉。
		if (currentUser.getPhone().equals(currentUser.getUsername())) {
			commentReply.setUserName(currentUser.getUsername().substring(0, 9) + "****");
		} else {
			commentReply.setUserName(currentUser.getUsername());
		}
		try {
			commentReply = (CommentReply) baseService.saveNow(commentReply);
			if (!StringUtils.isEmpty(comment.getReplyIds())) {
				comment.setReplyIds(comment.getReplyIds() + ";" + commentReply.getId());
			} else {
				comment.setReplyIds(commentReply.getId() + "");

			}
			commentReplyService.updateAndEvit(comment);// 会删除对应的缓存
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(comment);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("success");
			rr.setObject(null);
		}
		return rr;
	}

	/**
	 * 
	 * 添加回复。
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/getReplys")
	@ResponseBody
	public Object getReplys(long commentId) {
		ResponseResult rr = new ResponseResult();

		Comment comment = baseService.getById(Comment.class, commentId);
		if (comment == null) {
			rr.setInfo("评论不存在");
			return rr;
		}
		if (StringUtils.isEmpty(comment.getReplyIds())) {
			rr.setCode(1);
			rr.setObject(new ArrayList<CommentReply>());// 空的 回复列表
			return null;
		}
		try {
			if (StringUtils.isEmpty(comment.getReplyIds())) {
				rr.setCode(1);
				rr.setInfo("success");
				rr.setObject(new ArrayList<CommentReply>());
				return rr;// 返回空的列表
			}
			List<CommentReply> replys = commentReplyService.get(comment);// 会存入缓存
			rr.setCode(1);
			rr.setInfo("success");
			rr.setObject(replys);
		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("success");
			rr.setObject(null);
		}
		return rr;
	}

}
